package wap.rockvilletech.util.imaging;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sourceforge.wurfl.core.Device;
import net.sourceforge.wurfl.core.WURFLHolder;
import net.sourceforge.wurfl.core.WURFLManager;

import org.apache.log4j.Logger;

import wap.rockvilletech.portal.SystemProperty;
import wap.rockvilletech.portal.UGreetingsBean;
import wap.rockvilletech.portal.WapPortalBean;


/**
 *
 * @author Tasnim
 */
@SuppressWarnings("serial")
public class UcardDownloadHelper extends HttpServlet {
	
    private static final Logger log = Logger.getLogger(UcardDownloadHelper.class);
    private static String originalContentPath ;

    @Override
    public void init() throws ServletException {
        super.init();
        originalContentPath = SystemProperty.getProperty("ugreetings_content_basepath");
    }
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        HashMap hm_Content=new HashMap();
        ArrayList arr_cnt=new ArrayList();

        String brand = "";
        String model = "";
        String wd = "0";
        String ht = "0";
        String imgPath = "";
        String price = "";
        String contentChargeId = "0";
        int dloadStatus=0;        
        String strSeqId=request.getParameter("sid")!=null?request.getParameter("sid"):"";
        if(strSeqId.isEmpty()) {
        	log.warn("Invalid Request, card download id not valid, sid="+strSeqId);        	
        	return;
        }
        int wurfl_screenWidth=170;
        int wurfl_screenHeight=220;
        ArrayList arr_CardInfo = new ArrayList();
        ProcessUCard puc = new ProcessUCard();

        try {
        	WURFLHolder wurflHolder = (WURFLHolder) getServletContext().getAttribute("net.sourceforge.wurfl.core.WURFLHolder");
            WURFLManager wurfl = wurflHolder.getWURFLManager();
            Device device = wurfl.getDeviceForRequest(request);

            brand = device.getCapability("brand_name");
            model = device.getCapability("model_name");

            wurfl_screenWidth = Integer.parseInt(device.getCapability("max_image_width")); // Width from Wurfl //max_image_width
            // Width from Wurfl //max_image_height
            wurfl_screenHeight = Integer.parseInt(device.getCapability("max_image_height")); // Width from Wurfl //max_image_height

            wd =Integer.toString(wurfl_screenWidth);
            ht = Integer.toString(wurfl_screenHeight);
        }
        catch(Exception ex) {
        	log.error("get Wurfl Properties ",ex);
        }
        try {        	
            UGreetingsBean ugb = new UGreetingsBean();        	
            arr_cnt = ugb.getCardDetail(strSeqId);
            hm_Content.put("cid", arr_cnt.get(0));
            hm_Content.put("Point1", arr_cnt.get(1).toString());
            hm_Content.put("Point2", arr_cnt.get(2).toString());
            hm_Content.put("Bias", arr_cnt.get(3).toString());
            hm_Content.put("FillColor", arr_cnt.get(4).toString());
            
            log.debug("seqid = " + strSeqId);
            
            //Get from DB where GSM is equal this and this

            arr_CardInfo = ugb.getSendCardDetail(strSeqId);

            //-- boolean isDownloadAllowed=ufoneGreetingCardDb.getDownloadedCounts_ReciverGreetingCard_ContentId(msisdn,seqId);
            if(arr_CardInfo.isEmpty()){
            	printTextResponse(response, "<div align='center'>Dear User, Card ID not validated, please try with correct card id</div>");
            	return;
            }
            else{
                try {
                	dloadStatus =Integer.parseInt(arr_CardInfo.get(4).toString());
                	contentChargeId = arr_CardInfo.get(5).toString();
                } catch(Exception e){
                    dloadStatus = 99;
                }
                if(dloadStatus > 1) {
                	printTextResponse(response, "<div align='center'>Dear User, Your request is expired as you have downloaded this UGreetings Card!</div>");
                	return;
                }
            }
             
            boolean isSuccessfullyDownloaded = true;
            
            ServletOutputStream sos = response.getOutputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int h = Integer.parseInt(ht);
            int w = Integer.parseInt(wd);
            // Call Customizing Image Method and get imgage
            
            imgPath = originalContentPath + arr_cnt.get(5).toString();
            price = arr_cnt.get(6).toString();

            byte[] bytes;
            hm_Content.put("imgPath", imgPath);
            hm_Content.put("w", w);
            hm_Content.put("h", h);
            hm_Content.put("recvName", arr_CardInfo.get(2).toString());
            hm_Content.put("sndrName", arr_CardInfo.get(3).toString());
            BufferedImage image = puc.processCard(hm_Content);
            //--BufferedImage image = puc.processCard(imgPath, arr_CardInfo.get(2).toString(), arr_CardInfo.get(3).toString(), w, h);

            response.setContentType("image/jpeg");
            ImageIO.write(image, "jpeg", baos);
            bytes = null;
            bytes = baos.toByteArray();
            try {
                sos.write(bytes);
            } catch (Exception e) {
                isSuccessfullyDownloaded = false;
                log.error("Error writing image to servlet outpust stream having savegreetingcardinfo Table seqid: " + strSeqId,e);
            }
            sos.close();
            
            if(isSuccessfullyDownloaded) {
                ugb.setUpdateStatus(strSeqId);
                new WapPortalBean().setContentDownloadStatus(contentChargeId, price, request.getRemoteHost(), brand, model);
            }

        } catch (Exception e) {
            log.error("Error constructing image to servlet outpust stream having request path " ,e);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

	/**
	 * prints text response on servlet output stream
	 * @param resp
	 * @param text
	 */
	private void printTextResponse(HttpServletResponse resp, String text) {
		try {
			resp.setContentType("text/html");
			PrintWriter out = resp.getWriter();
			out.print(text);
			out.close();
		} catch (IOException e) {
			log.error("printTextResponse("+text+")", e);
		}		
	}
}
